package com.aizuda.boot.modules.business.contract.mapper;

import com.aizuda.boot.modules.business.contract.entity.ContractFieldEntity;
import com.aizuda.boot.modules.business.contract.entity.vo.ContractDTO;
import com.aizuda.boot.modules.business.contract.entity.vo.FieldDTO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * @Author sangyirong
 * @ClassName ContractFieldMapper
 * @Version 1.0
 * @Date 2025/5/29 18:12
 */
@Mapper
public interface ContractFieldMapper extends BaseMapper<ContractFieldEntity> {
    /**
     * 查询申请人字段ID
     *
     * @return
     */
    @Select("SELECT id FROM contract_field WHERE field_name = '申请人'")
    Long findHandlerFieldId();

    /**
     * 根据父字段ID查询子字段
     *
     * @param parentFieldId
     * @return
     */
    @Select("SELECT * FROM contract_field WHERE parent_field_id = #{parentFieldId} ORDER BY id")
    List<ContractFieldEntity> findSubFieldsByParentId(@Param("parentFieldId") Long parentFieldId);

    /**
     * 根据ID查询字段
     * @param ids
     * @return
     */
    List<ContractDTO.ModuleDTO.FieldDTO> findFieldByIds(@Param("ids") List<Integer> ids);

    /**
     * 查询所有字段
     * @return
     */
    @Select("select * from contract_field where field_type!='GROUP'")
    List<FieldDTO> findAllHeaders();

    /**
     * 根据字段名称模糊查询字段
     * @param fieldName 字段名称（支持模糊匹配）
     * @return
     */
    @Select("select * from contract_field where field_type!='GROUP' and field_name like concat('%', #{fieldName}, '%')")
    List<FieldDTO> findHeadersByFieldName(@Param("fieldName") String fieldName);

    /**
     * 获取所有字段
     *
     * @return 字段列表
     */
    @Select("SELECT * FROM contract_field ORDER BY id")
    List<ContractFieldEntity> selectAllFields();

    /**
     * 根据字段code查询字段ID
     *
     * @param code 字段编码
     * @return 字段ID
     */
    @Select("SELECT id FROM contract_field WHERE code = #{code} AND is_enabled = 1")
    Long findIdByCode(@Param("code") String code);

    /**
     * 根据字段code查询字段实体
     *
     * @param code 字段编码
     * @return 字段实体
     */
    @Select("SELECT * FROM contract_field WHERE code = #{code} AND is_enabled = 1")
    ContractFieldEntity findByCode(@Param("code") String code);

    /**
     * 批量根据字段codes查询字段实体
     *
     * @param codes 字段编码列表
     * @return 字段实体列表
     */
    @Select({
            "<script>",
            "SELECT * FROM contract_field ",
            "WHERE code IN ",
            "<foreach item='code' collection='codes' open='(' separator=',' close=')'>",
            "  #{code}",
            "</foreach>",
            "AND is_enabled = 1",
            "</script>"
    })
    List<ContractFieldEntity> findByCodes(@Param("codes") List<String> codes);
}